package com.bookshop.util;

import com.bookshop.entity.wx.WxTokenInfo;
import com.bookshop.entity.wx.WxUserInfo;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @author g2l
 * @create 2024-01-21 13:23
 */
@Slf4j
public class WxUserUtil {
    // 根据code去访问微信服务器获取token，根据token访问微信服务器获取用户信息
    public static WxUserInfo getUserInfo(String code, String appId, String secret) throws IOException {
        HttpClient httpClient = HttpClients.createDefault();
        // 用code去换取token
        String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + secret +
                "&code=" + code + "&grant_type=authorization_code";
        HttpGet httpGetToken = new HttpGet(tokenUrl);
        // 接收返回的token
        String responseResult = "";
        HttpResponse tokenResponse = httpClient.execute(httpGetToken);
        if (tokenResponse.getStatusLine().getStatusCode() == 200) {
            responseResult = EntityUtils.toString(tokenResponse.getEntity(), "UTF-8");
        }
        log.info("获取token的返回结果是" + responseResult);
        // 将结果封装到对象中
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
        Gson gson = gsonBuilder.create();

        WxTokenInfo wxTokenInfo = gson.fromJson(responseResult, WxTokenInfo.class);
        // 用token去访问用户数据
        String userUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + wxTokenInfo.getAccessToken() +
                "&openid=" + wxTokenInfo.getUnionid()  + "&lang=zh_CN";
        HttpGet httpGetUser = new HttpGet(userUrl);
        // 接收返回的user信息
        HttpResponse userResponse = httpClient.execute(httpGetUser);
        if (userResponse.getStatusLine().getStatusCode() == 200) {
            responseResult = EntityUtils.toString(userResponse.getEntity(), "UTF-8");
        }
        log.info("获取个人信息的返回结果是" + responseResult);
        // 封装成用户对象并返回
        return gson.fromJson(responseResult, WxUserInfo.class);
    }
}
